package com.jesterplayer.fragment;

import android.content.ContentResolver;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Audio.Albums;
import android.provider.MediaStore.Audio.Artists;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.Audio.Genres;
import android.provider.MediaStore.Audio.Playlists;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;
import com.jesterplayer.NowPlayingActivity;
import com.jesterplayer.PlaybackController;
import com.jesterplayer.R;
import com.jesterplayer.adapter.TrackAdapter;

public class TracksFragment extends SherlockFragment implements
		LoaderCallbacks<Cursor>, OnItemClickListener {

	private final static String MIME_TYPE = "mimetype";
	public final static String EXTERNAL = "external";	
	// Adapter
	private TrackAdapter mTrackAdapter;

	// ListView
	private ListView mListView;

	// Cursor
	private Cursor mCursor;

	// Playlist ID
	private long mPlaylistId = -1;

	// Selected position
	private int mSelectedPosition;

	// Used to set ringtone
	private long mSelectedId;

	// Options
	private final int PLAY_SELECTION = 6;

	private final int USE_AS_RINGTONE = 7;

	private final int ADD_TO_PLAYLIST = 8;

	private final int SEARCH = 9;

	private final int REMOVE = 10;

	private boolean mEditMode = false;
	
	// Audio columns
	public static int mTitleIndex, mAlbumIndex, mArtistIndex, mMediaIdIndex, mMediaData;
	private final static long[] sEmptyList = new long[0];
	// Bundle
	public TracksFragment() {
	}

	public TracksFragment(Bundle args) {
		setArguments(args);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// Adapter
		mTrackAdapter = new TrackAdapter(getActivity(),
				R.layout.listview_items, null, new String[] {}, new int[] {}, 0);
		mListView.setOnCreateContextMenuListener(this);
		mListView.setOnItemClickListener(this);
		mListView.setAdapter(mTrackAdapter);

		// Important!
		getLoaderManager().initLoader(0, null, this);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View root = inflater.inflate(R.layout.listview, container, false);
		mListView = (ListView) root.findViewById(android.R.id.list);

		return root;
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		String[] projection = new String[] { BaseColumns._ID,
				MediaColumns.TITLE, AudioColumns.ALBUM, AudioColumns.ARTIST, MediaColumns.DATA, MediaColumns.DISPLAY_NAME};
		StringBuilder where = new StringBuilder();
		String sortOrder = Audio.Media.DEFAULT_SORT_ORDER;
		where.append(AudioColumns.IS_MUSIC + "=1").append(
				" AND " + MediaColumns.TITLE + " != ''");
		Uri uri = Audio.Media.EXTERNAL_CONTENT_URI;
		
		if (getArguments() != null) {
			mPlaylistId = getArguments().getLong(BaseColumns._ID);
			String mimeType = getArguments().getString("mimetype");
			if (Audio.Playlists.CONTENT_TYPE.equals(mimeType)) {
				where = new StringBuilder();
				where.append(AudioColumns.IS_MUSIC + "=1");
				where.append(" AND " + MediaColumns.TITLE + " != ''");
				switch ((int) mPlaylistId) {
				default:
					if (id < 0)
						return null;
					projection = new String[] { Playlists.Members._ID,
							Playlists.Members.AUDIO_ID, MediaColumns.TITLE,
							AudioColumns.ALBUM, AudioColumns.ARTIST,
							AudioColumns.DURATION };

					uri = Playlists.Members
							.getContentUri(EXTERNAL, mPlaylistId);
					sortOrder = Playlists.Members.DEFAULT_SORT_ORDER;
					break;
				}
			} else if (Audio.Genres.CONTENT_TYPE.equals(mimeType)) {
				long genreId = getArguments().getLong(BaseColumns._ID);
				uri = Genres.Members.getContentUri(EXTERNAL, genreId);
				projection = new String[] { BaseColumns._ID,
						MediaColumns.TITLE, AudioColumns.ALBUM,
						AudioColumns.ARTIST };
				where = new StringBuilder();
				where.append(AudioColumns.IS_MUSIC + "=1").append(
						" AND " + MediaColumns.TITLE + " != ''");
				sortOrder = Genres.Members.DEFAULT_SORT_ORDER;
			} else {
				if (Audio.Albums.CONTENT_TYPE.equals(mimeType)) {
					long albumId = getArguments().getLong(BaseColumns._ID);
					where.append(" AND " + AudioColumns.ALBUM_ID + "="
							+ albumId);
					sortOrder = Audio.Media.TRACK + ", " + sortOrder;
				} else if (Audio.Artists.CONTENT_TYPE.equals(mimeType)) {
					sortOrder = MediaColumns.TITLE;
					long artist_id = getArguments().getLong(BaseColumns._ID);
					where.append(" AND " + AudioColumns.ARTIST_ID + "="
							+ artist_id);
				}
			}
		}
		return new CursorLoader(getActivity(), uri, projection,
				where.toString(), null, sortOrder);
	}
	
	public void playTrackFromPlaylist(final long playListID) {
        final ContentResolver resolver = getActivity().getContentResolver();
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playListID);
    final String dataKey = MediaStore.Audio.Media.DATA;
    Cursor tracks = resolver.query(uri, new String[] { dataKey }, null, null, null);
    if (tracks != null) {
        tracks.moveToFirst();
        final int dataIndex = tracks.getColumnIndex(dataKey);
        final String dataPath = tracks.getString(dataIndex);
        playAudio(dataPath);
        tracks.close();
    }
	}
    public static void playAudio(final String path) {
        final MediaPlayer player = new MediaPlayer();
        if (path == null) {
            Log.e("lol", "Called playAudio with null data stream.");
            return;
        }
        try {
            player.setDataSource(path);
            player.prepare();
            player.start();
        } catch (Exception e) {
            Log.e("lol", "Failed to start MediaPlayer: " + e.getMessage());
            return;
        }
    }
	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		// Check for database errors
		if (data == null) {
			return;
		}
		
		/*if (getArguments() != null
				&& Playlists.CONTENT_TYPE.equals(getArguments().getString(
						MIME_TYPE))
				&& (getArguments().getLong(BaseColumns._ID) >= 0 || getArguments()
						.getLong(BaseColumns._ID) == PLAYLIST_FAVORITES)) {
			mMediaIdIndex = data
					.getColumnIndexOrThrow(Playlists.Members.AUDIO_ID);
			mTitleIndex = data.getColumnIndexOrThrow(MediaColumns.TITLE);
			mAlbumIndex = data.getColumnIndexOrThrow(AudioColumns.ALBUM);
			// FIXME
			// mArtistIndex =
			// data.getColumnIndexOrThrow(Playlists.Members.ARTIST);
		} else */
		if (getArguments() != null
				&& Genres.CONTENT_TYPE.equals(getArguments().getString(
						MIME_TYPE))) {
			mMediaIdIndex = data.getColumnIndexOrThrow(BaseColumns._ID);
			mTitleIndex = data.getColumnIndexOrThrow(MediaColumns.TITLE);
			mArtistIndex = data.getColumnIndexOrThrow(AudioColumns.ARTIST);
			mAlbumIndex = data.getColumnIndexOrThrow(AudioColumns.ALBUM);
		} else if (getArguments() != null
				&& Artists.CONTENT_TYPE.equals(getArguments().getString(
						MIME_TYPE))) {
			mTitleIndex = data.getColumnIndexOrThrow(MediaColumns.TITLE);
			// mArtistIndex is "line2" of the ListView
			mArtistIndex = data.getColumnIndexOrThrow(AudioColumns.ALBUM);
		} else if (getArguments() != null
				&& Albums.CONTENT_TYPE.equals(getArguments().getString(
						MIME_TYPE))) {
			mMediaIdIndex = data.getColumnIndexOrThrow(BaseColumns._ID);
			mTitleIndex = data.getColumnIndexOrThrow(MediaColumns.TITLE);
			mArtistIndex = data.getColumnIndexOrThrow(AudioColumns.ARTIST);
		} else {
			mMediaIdIndex = data.getColumnIndexOrThrow(BaseColumns._ID);
			mTitleIndex = data.getColumnIndexOrThrow(MediaColumns.TITLE);
			mArtistIndex = data.getColumnIndexOrThrow(AudioColumns.ARTIST);
			mAlbumIndex = data.getColumnIndexOrThrow(AudioColumns.ALBUM);
		}
		
		mMediaData = data.getColumnIndexOrThrow(MediaColumns.DATA);
		
		mTrackAdapter.changeCursor(data);
		mCursor = data;
		
	}
	
/*	public static String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }*/

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		if (mTrackAdapter != null)
			mTrackAdapter.changeCursor(null);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putAll(getArguments() != null ? getArguments() : new Bundle());
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) 
	{
       String playme = mCursor.getString(TracksFragment.mMediaData);
		
		mCursor.moveToFirst();
		for (int i = 0; mCursor.moveToNext(); i++) {
			PlaybackController.addToSongList(mCursor.getString(mMediaData));
	        NowPlayingActivity.addToList(mCursor.getString(mTitleIndex));
			if (mCursor.getString(mMediaData).equals(playme))
				PlaybackController.playSong(playme, i);
		}

		// TODO Auto-generated method stub
	}
	
	public static long[] getSongListForCursor(Cursor cursor) {
        if (cursor == null) {
            return sEmptyList;
        }
        int len = cursor.getCount();
        long[] list = new long[len];
        cursor.moveToFirst();
        int colidx = -1;
        try {
            colidx = cursor.getColumnIndexOrThrow(Audio.Playlists.Members.AUDIO_ID);
        } catch (IllegalArgumentException ex) {
            colidx = cursor.getColumnIndexOrThrow(BaseColumns._ID);
        }
        for (int i = 0; i < len; i++) {
            list[i] = cursor.getLong(colidx);
            cursor.moveToNext();
        }
        return list;
    }
	
	/*
	 * public View onCreateView(LayoutInflater inflater, ViewGroup container,
	 * Bundle savedInstanceState) { View view =
	 * inflater.inflate(R.layout.activity_library, container, false); return
	 * view; }
	 * 
	 * public void setText(String item) { TextView view = (TextView)
	 * getView().findViewById(R.id.text_context); view.setText(item); }
	 */
}